//
//  MAHomeChildViewController.m
//  meiang_edu
//
//  Created by Liubi_Chaos_G on 2018/7/30.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MAHomeChildViewController.h"

#import "MAHomeModel.h"
#import "MANoImgCell.h"
#import "MAOneImgCell.h"
#import "MAThreeImgsCell.h"
#import "MAHomeWatchCell.h"
#import "MAJiGouModel.h"
#import "MAHomeWatchCell.h"
#import "MAWorkDetailVC.h"


#define CollectionViewCell @"CollectionViewCell"

@interface MAHomeChildViewController ()<UITableViewDelegate, UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;

/** models */
@property(nonatomic,strong) NSMutableArray *models;

/** jigouModels */
@property(nonatomic,strong) NSMutableArray *jigouModels;

/** collectionView */
@property(nonatomic,strong) UICollectionView *collectionView;

/** headerView */
@property(nonatomic,strong) UIView *headerView;

@end

@implementation MAHomeChildViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupBasic];
    
    [self setupTableView];
    
}
- (void)setupBasic {
    self.view.backgroundColor = PROJECT_BG_COLOR;
    
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([MAHomeWatchCell class]) bundle:nil] forCellWithReuseIdentifier:CollectionViewCell];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideFollowList) name:kMAHideJiGouFollowListNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(extendFollowList) name:kMAExtendJiGouFollowListNotification object:nil];
}

- (void)hideFollowList {
    if ([self.title isEqualToString:@"资讯"]) {
        self.myTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        [self.myTableView reloadData];
    }
}
- (void)extendFollowList {
    if ([self.title isEqualToString:@"资讯"]) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 70)];
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 70, SCREEN_WIDTH, 4)];
        view.backgroundColor = PROJECT_BG_COLOR;
        [headerView addSubview:self.collectionView];
//        [headerView addSubview:view];
        self.myTableView.tableHeaderView = headerView;
        self.headerView = headerView;
        
    }
}

- (void)setupTableView {
    self.myTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    self.myTableView.tableFooterView = [UIView new];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self.myTableView.mj_header beginRefreshing];
    
    self.myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.myTableView.mj_footer.hidden = YES;
}

- (void)loadMoreData {
    
}

- (void)requestFollowData {
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@?entity_type=first_organizations&status=1",BASE_LISTENTITY_LIST,userinfo.ID];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            self.jigouModels = [MAJiGouModel mj_objectArrayWithKeyValuesArray:dataDict[@"value"]];
            if (self.jigouModels.count) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.headerView.height = 70;
                    self.collectionView.height = 70;
                });
                [self.collectionView reloadData];
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.headerView.height = 0;
                    self.collectionView.height = 0;
                });
            }
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.headerView.height = 0;
                self.collectionView.height = 0;
            });
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.headerView.height = 0;
            self.collectionView.height = 0;
        });
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
    }];
}

- (void)loadData {
    
    [self requestFollowData];
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
//    if (!userinfo.token) {
//        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
//        return;
//    }
//    [MBManager showLoading];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@?msgtype=%@",PICKUP_MSG_LIST,userinfo.ID,self.title];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        [self.myTableView.mj_header endRefreshing];
        self.myTableView.mj_footer.hidden = NO;
        [self.myTableView.mj_footer endRefreshingWithNoMoreData];
//        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            self.models = [MAHomeModel mj_objectArrayWithKeyValuesArray:dataDict[@"value"]];
            [self.myTableView reloadData];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
        [self.myTableView.mj_header endRefreshing];
        self.myTableView.mj_footer.hidden = NO;
        [self.myTableView.mj_footer endRefreshingWithNoMoreData];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.models.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
//    NSInteger section = indexPath.section;
    MAHomeModel *model = self.models[row];
    return model.cellHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    UITableViewCell *cell;
    MAHomeModel *model = self.models[row];
    if ([model.message_image_count integerValue] == 0) { // 无图
        MANoImgCell *noCell = [MANoImgCell cellWithTableView:tableView];
        noCell.model = model;
        cell = noCell;
    } else if ([model.message_image_count integerValue] < 2) { // 1图
        
        MAOneImgCell *oneCell = [MAOneImgCell cellWithTableView:tableView];
        oneCell.model = model;
        cell = oneCell;
    } else { // 三图
        
        MAThreeImgsCell *threeCell = [MAThreeImgsCell cellWithTableView:tableView];
        threeCell.model = model;
        cell = threeCell;
    }
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DLog(@"");
    NSInteger row = indexPath.row;
    MAHomeModel *model = self.models[row];
}


#pragma mark - collectionViewDelegate & datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.jigouModels.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(70, 70);
}
//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 10, 0, 10);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MAHomeWatchCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CollectionViewCell forIndexPath:indexPath];
    MAJiGouModel *model = self.jigouModels[indexPath.item];
    cell.model = model;
    return cell;
}


#pragma mark - getter & setter
- (NSMutableArray *)models {
    if (_models == nil) {
        _models = [NSMutableArray array];
    }
    return _models;
}
- (NSMutableArray *)jigouModels {
    if (_jigouModels == nil) {
        _jigouModels = [NSMutableArray array];
    }
    return _jigouModels;
}

- (UICollectionView *)collectionView {
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 70) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}
@end
